<template>
  <div class="page-miH page-bgBack pb32">
    <div class="uplaodBoxs">
      <div class="spin-content pt24">
        <div class="ant-upload-select-text-box">
          <a-form :form="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 8 }">
            <a-form-item label="发薪批次名称">
              <a-input
                placeholder="请输入"
                :maxLength="50"
                v-decorator="['orderTitle', { rules: [{ required: true, message: '发薪批次名称不能为空' }] }]"
              />
            </a-form-item>
            <a-form-item label="到账方式">
              <a-select
                v-decorator="[
                  'type',
                  {
                    rules: [
                      {
                        required: true,
                        message: '到账方式不能为空'
                      }
                    ]
                  }
                ]"
                placeholder="请选择"
              >
                <a-select-option :value="item.id" v-for="item in typeArr" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="选择用工单位">
              <a-select
                show-search
                :filter-option="filterOption"
                v-decorator="[
                  'companyId',
                  {
                    rules: [
                      {
                        required: true,
                        message: '用工单位不能为空'
                      }
                    ]
                  }
                ]"
                placeholder="请选择"
              >
                <a-select-option :value="item.id" v-for="item in companyIdArr" :key="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="备注">
              <a-textarea placeholder="请输入" :auto-size="{ minRows: 2, maxRows: 15 }" v-decorator="['remark']" />
            </a-form-item>
          </a-form>
          <a-form-item class="ml6" :wrapper-col="{ span: 24 }">
            <a-upload ref="upload" :showUploadList="false" :file-list="fileList" :before-upload="beforeUpload">
              <a-button icon="plus" type="primary" style="width: 240px; margin-left: 12px"> 导入发薪表 </a-button>
            </a-upload>
          </a-form-item>
        </div>
      </div>
      <div class="tipBox">
        <a-row style="color: #55565d; font-size: 16px; font-weight: 500; padding-bottom: 16px"> 导入说明 </a-row>
        <a-row>
          <a-col :span="12">
            <div class="mb10">
              1、请使用模板上传
              <span @click="download('zfbBatchTemplate.xlsx', '支付宝发薪模板')" class="add-primary"> 「支付宝发薪模板」 </span>
              <span @click="download('vxBatchTemplate.xlsx', '微工卡发薪模板')" class="add-primary"> 「微工卡发薪模板」 </span>
              <span @click="download('bankBatchTemplate.xlsx', '银行卡发薪模板')" class="add-primary"> 「银行卡发薪模板」 </span>
            </div>
            <div class="mb10">2、上传的发薪表，必须包含以下信息： 姓名、身份证号</div>
            <div class="mb10">2、不支持合并单元格上传</div>
          </a-col>
        </a-row>
      </div>
    </div>
  </div>
</template>
<script>
import { getToken } from "xqjr-module-auth";
import axios from "axios";
import qs from "qs";
import { getCompanyUnits } from "../api";

export default {
  data() {
    return {
      confirmLoading: false,
      form: this.$form.createForm(this, {}),
      companyIdArr: [],
      typeArr: [
        { id: 1, name: "支付宝" },
        { id: 2, name: "微工卡" },
        { id: 3, name: "银行卡" }
      ],
      id: "",
      data: {},
      fileList: [],
      uploading: false,
      selectedRowKeys: [],
      headers: {},
      file: "",
      action: "",
      uploadImg: require("@/assets/img/uploadImg.png")
    };
  },
  created() {
    this.headers = {
      token: getToken(),
      "Content-Type": "multipart/form-data"
    };
    this.id = this.$store.state.hr.companyId;
    this.action = `/salary/api/v1/empFixedSalaries/import?companyId=${this.id}&force=false`;
    this.onGetCompanyUnits();
  },
  methods: {
    async onGetCompanyUnits() {
      try {
        const { data } = await getCompanyUnits({
          pageNo: 1,
          pageSize: 1000
        });
        this.companyIdArr = data;
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    beforeUpload(file) {
      if (this.fileList.length > 0) {
        this.$message.error("最多只能上传一个");
        return false;
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          let companyName = "";
          this.companyIdArr.map(e => {
            if (e.id === values.companyId) companyName = e.name;
          });
          this.fileList = [...this.fileList, file];
          if (this.fileList && this.fileList.length > 0) {
            const { fileList } = this;
            const formData = new FormData();
            fileList.forEach(file => {
              formData.append("file", file);
              formData.append("companyId", values.companyId);
              formData.append("companyName", companyName);
              formData.append("type", values.type);
              formData.append("orderTitle", values.orderTitle);
              formData.append("remark", values.remark || "");
            });
            this.uploading = true;
            axios({
              url: `/hr/api/v1/transferAccountsBatches/saveBatchAndDetailByFile`,
              method: "post",
              data: formData,
              headers: this.headers
            })
              .then(res => {
                this.handleSuccess(res.data);
                this.uploading = false;
              })
              .catch(() => {
                setTimeout(() => {
                  this.reset();
                }, 1000);
                this.$notification["error"]({
                  message: "error",
                  description: "上传失败"
                });
              });
          } else {
            this.handleUploadError();
          }
        }
      });

      return false;
    },
    handleUploadError() {
      // this.$message.warning("没有文件");
      setTimeout(() => {
        this.reset();
      }, 1000);
    },
    handleSuccess(res) {
      var that = this;

      if (res.code === 200) {
        if (res.data) {
          this.$confirm({
            okText: "确定",
            title: `上传成功`,
            onOk() {
              if (res.data.failTransferAccountsDetailAddDTOList.length > 0) {
                sessionStorage.setItem("paySalaryInfoId", res.data.transferAccountsBatchVO.id);
                sessionStorage.setItem("dataType", res.data.transferAccountsBatchVO.type);
                that.$emit("upData", res.data.failTransferAccountsDetailAddDTOList);
              } else {
                that.$router.replace({
                  name: "applyForInfo",
                  query: { id: res.data.transferAccountsBatchVO.id, dataType: res.data.transferAccountsBatchVO.type }
                });
              }
            }
          });
        } else {
          this.$notification["error"]({
            message: "error",
            description: "上传失败"
          });
        }
      } else if (res.data === null) {
        this.$confirm({
          okText: "确定",
          title: res.msg,
          cancelButtonProps: false
        });
      } else {
        this.$notification["error"]({
          message: "error",
          description: res.msg || "上传失败"
        });
      }
      setTimeout(() => {
        this.reset();
      }, 1000);
    },
    download(templateName, name) {
      const token = this.$store.state.auth.token;
      let params = {};
      params = {
        templateName
      };

      axios({
        url: `/hr/api/v1/excel/template/download`,
        params,
        paramsSerializer: param => {
          return qs.stringify(param, { indices: false });
        },
        method: "GET",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", `${name}.xlsx`);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          console.log("error log --> ", err);
        });
    },
    reset() {
      this.fileList = [];
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    }
  }
};
</script>
<style lang="scss" scoped>
.exportTitle {
  text-align: center;
  font-size: 16px;
  font-weight: 500;
  color: #252525;
}
.left2 {
  z-index: 3;
  left: 50px;
  position: absolute;
  color: #595959;
  font-size: 14px;
}
.tipBox {
  line-height: 18px;
  background: #faf9f9;
  border-radius: 4px;
  font-size: 12px;
  color: #595959;
  margin: 0 24px;
  width: calc(100% - 48px) !important;
  padding: 24px;
  border-radius: 4px;
}
.ant-upload-select-text-box {
  background: #fff;
  margin: 0 24px 24px 24px;
  text-align: center;
  border-radius: 4px;
  padding: 24px;
  box-shadow: 0px 6px 16px 8px rgba(0, 0, 0, 0.03), 0px 4px 8px 0px rgba(0, 0, 0, 0.04);
  ::v-deep .ant-form-item-label > label {
    font-weight: normal !important;
    color: #55565d !important;
  }
  ::v-deep #remark {
    height: 80px !important;
  }
}
.ant-upload-select-text-box ::v-deep .ant-upload-list {
  display: none;
}
.ant-upload-list-item-name {
  text-align-last: left;
}

.anticon-upload {
  font-size: 40px;
}

.add-primary {
  color: var(--primary);
  font-size: 12px;
  cursor: pointer;
}
</style>
